package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@SuppressWarnings("all")
@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {

    @Autowired
    PaymentService paymentService;
    @Value("${server.port}")
    private String portServer;


    //新增一个payment对象
    @PostMapping("/save")
    public CommonResult<Payment>create(@RequestBody Payment payment){
        try{
            int result=paymentService.createPayment(payment);
            log.info("****result:"+result);
            if(result>0){
                log.info("****id:"+payment.getId());
                return new CommonResult<Payment>(200,"新增成功",payment);
            }
        }catch (Exception e){
            log.error(e.getLocalizedMessage(),e);
        }
        return new CommonResult<Payment>(444,"新增失败");
    }
    //通过id获取到Payement对象
    //Mybatis_获取自增主键的两种方式
    @GetMapping("/getPaymentById/{id}")
    public CommonResult<Payment>getPaymentById(@PathVariable Long id){
         try{
             Payment payment = paymentService.getPaymentById(id);
             if(payment!=null){
                 log.info("*****port:"+portServer);
                 return new CommonResult<Payment>(200,"查询成功port:"+portServer,payment);
             }
         }catch (Exception e){
              log.error(e.getLocalizedMessage(),e);
         }
        return new CommonResult<Payment>(444,"查询失败");
    }
    @GetMapping(value = "/lb")
    public String getPaymentLB(){
        return portServer;
    }

    //feign 客户端默认1s,如果超过会报错误页面
    @GetMapping("/timeout")
    public String timeout(){
        try { TimeUnit.SECONDS.sleep(3);  } catch (InterruptedException e) {e.printStackTrace();}
        return portServer;
    }
}
